package com.scs.application.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.sys.entity.RoleUser;
import com.scs.application.modules.sys.mapper.RoleUserMapper;
import com.scs.application.modules.sys.service.RoleUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class RoleUserServiceImpl extends BaseServiceImpl<RoleUserMapper, RoleUser> implements RoleUserService {
    @Override
    public Boolean saveByUsers(String roleId, String userIds) {
        // 先删除此角色的用户
        remove(new QueryWrapper<RoleUser>().eq("role_id",roleId));
        // 将用户列表保存
        Collection<RoleUser> roleUsers = new ArrayList<>();
        String[] userIdArray = userIds.split(",");
        for (String userId:userIdArray) {
            if (StringUtils.isBlank(userId)) continue;
            RoleUser roleUser = new RoleUser();
            roleUser.setRoleId(roleId);
            roleUser.setUserId(userId);
            roleUsers.add(roleUser);
        }
        saveBatch(roleUsers,1000);
        return true;
    }
    @Override
    public List<RoleUser> getByRoleId(String roleId) {
        return list(new QueryWrapper<RoleUser>().eq("role_id",roleId));
    }

    @Override
    public void addUserIds(String roleId, String userIds) {
        String[] userIdArray = userIds.split(",");

        // 先删除此角色的用户，防止重复添加
        remove(new QueryWrapper<RoleUser>().eq("role_id",roleId).in("user_id",userIdArray));

        // 将用户列表保存
        Collection<RoleUser> roleUsers = new ArrayList<>();
        for (String userId:userIdArray) {
            if (StringUtils.isBlank(userId)) continue;
            RoleUser roleUser = new RoleUser();
            roleUser.setRoleId(roleId);
            roleUser.setUserId(userId);
            roleUsers.add(roleUser);
        }
        saveBatch(roleUsers,1000);
    }

    /**
     * @Description：增加或者删除角色用户
     * @param  roleId           角色id
     * @param  addUserIds       需要添加的用户id列表
     * @param  deleteUserIds    需要删除的用户id列表
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrDelete(String roleId, String addUserIds,String deleteUserIds) {
        if (StringUtils.isNotBlank(addUserIds)) {
            this.addUserIds(roleId, addUserIds);
        }
        if (StringUtils.isNotBlank(deleteUserIds)) {
            String[] userIdArray = deleteUserIds.split(",");
            remove(new QueryWrapper<RoleUser>().eq("role_id",roleId).in("user_id",userIdArray));
        }
    }
}
